//
//  CNBuyGoldCoinController.m
//  chuiniu
//
//  Created by zheng ji on 14-10-12.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "CNBuyGoldCoinController.h"
#import <StoreKit/StoreKit.h>
#import "CNAppDelegate.h"
#import "iToast.h"
#import "CNGameUtil.h"
#import "CommandDef.h"
@interface CNBuyGoldCoinController ()
{
    NSArray* _products;
    
    CNAppDelegate* _appDelegate;
     iToast *toast;
    
    int _currentBuyProductIndex;//当前购买的产品序号
}
@end

@implementation CNBuyGoldCoinController

- (void)viewDidLoad {
    [super viewDidLoad];
     [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    _appDelegate=(CNAppDelegate*)[UIApplication sharedApplication].delegate;
    
     
    _appDelegate.gameClient.gameMainViewController=self;
       // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)viewDidAppear:(BOOL)animated{
    [self loadProducts];
    [self showToast:-1 title:@"正在加载数据..." duration:kToastDuration15Second position:kToastPositionCenter];
}
-(void)loadProducts{
    if(_appDelegate.goldCoinProducts==nil) return;
    
    if([SKPaymentQueue canMakePayments]){
        
        NSMutableSet* set=[[NSMutableSet alloc]init];
        
        for (NSDictionary* dict in _appDelegate.goldCoinProducts) {
            NSString* productId=[dict objectForKey:@"productid"];
            
            [set addObject:productId];
        }
       // NSSet* set=[NSSet setWithArray:_appDelegate.goldCoinProduct.allKeys];
        
      
        
       SKProductsRequest* request=  [[SKProductsRequest alloc] initWithProductIdentifiers:set];
        
        request.delegate=self;
        [request start];
    }
    
    
    
    
    
}
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    
    for (SKPaymentTransaction* payTrans in transactions) {
       
        switch (payTrans.transactionState) {
            case SKPaymentTransactionStatePurchased:
                 [[SKPaymentQueue defaultQueue] finishTransaction:payTrans];
                [self buyGoldCoinResult:YES];
               
                break;
             case SKPaymentTransactionStateFailed:
                 [[SKPaymentQueue defaultQueue] finishTransaction:payTrans];
                [self buyGoldCoinResult:NO];
                break;
            default:
                break;
        }
    }
    
}
-(void)buySuccess{
    CNPlayer* player=[CNGameUtil getCurrentPlayerFromUserDefaults];//_appDelegate.player;
    int coins=[player.coins intValue];
    NSDictionary* dict=[_appDelegate.goldCoinProducts objectAtIndex:_currentBuyProductIndex];
    
    NSString* strgoldcoins=[dict objectForKey:@"goldcoins"];
    int buyCoins= [strgoldcoins intValue];
    NSString* strMoney=[dict objectForKey:@"money"];
    double money= [strMoney doubleValue];
    
    player.coins=[NSString stringWithFormat:@"%d",coins+ buyCoins];
    player.levelName=[CNGameUtil calcPlayerLevelName:coins+ buyCoins];//新的等级
    
    [CNGameUtil saveCurrentPlayerToUserDefaults:player];
    
    [_appDelegate.gameClient sendGoldCoinCommand:player coins:buyCoins tradeType:TradeTypeBuyGoldCoin money:money];
    
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"" message:[NSString stringWithFormat:@"已成功获得%d枚金币,您当前金币数：%@,等级:%@",buyCoins,player.coins,player.levelName] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [alertView show];
    alertView=nil;
 
}
-(void)buyGoldCoinResult:(BOOL)success{
    
    if(success){
        [self buySuccess];
        
    }else{
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"" message:@"购买金币失败!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alertView show];
        alertView=nil;

    }
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    [self hiddenToastView];
    _products=response.products;
    
    [self.tableView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    return _products==nil?0:_products.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReuseCell" forIndexPath:indexPath];
    
 
    
   cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    NSDictionary* dict=[_appDelegate.goldCoinProducts objectAtIndex:indexPath.row];
    
    NSString* productID=[dict objectForKey:@"productid"];
    
    //SKProduct* p=_products[indexPath.row];
    
    SKProduct* p=[self getSKProductById:productID];
    
    cell.textLabel.text=p.localizedTitle;
    cell.detailTextLabel.text=p.localizedDescription;
    
    return cell;
}
-(SKProduct*) getSKProductById:(NSString*) productId{

    for (SKProduct* p in _products) {
        if ([p.productIdentifier isEqualToString:productId]) {
            return p;
        }
    }
    return nil;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSDictionary* dict=[_appDelegate.goldCoinProducts objectAtIndex:indexPath.row];
    
    NSString* productID=[dict objectForKey:@"productid"];
    
    //SKProduct* p=_products[indexPath.row];
    _currentBuyProductIndex=indexPath.row;
    
    SKProduct* p=[self getSKProductById:productID];
    
    SKPayment* payment=[SKPayment paymentWithProduct:p];
    
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

-(void)hiddenToastView{
    if(toast !=nil){
        [toast hideToast:nil];
        toast=nil;
    }
    
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position{
    [self showToast:tag title:title duration:duration position:position countDown:YES];
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position countDown:(BOOL)countDown{
    
    [self hiddenToastView];
    toast = [iToast makeToast:title];
    toast.tag=tag;
   // toast.toastDelegate=self;
    toast.countDown=countDown;
    [toast setToastPosition:position];
    [toast setToastDuration:duration];
    [toast show];
}

@end
